import { useEffect, useState } from 'react';
import './App.css';

// 自定义HOOK，最牛的就是可以同步的使用异步
function useIsVip(uId){
  const [isVip, setIsVip] = useState(0);
  const [cache, setCache] = useState({});
  useEffect(() => {
    if(cache[uId] === undefined){
      setIsVip(0); // 初始化状态
      setTimeout(() => {
        var fetchRes = Math.random() > 0.5;
        cache[uId] = fetchRes;
        setCache({...cache}); // 缓存XHR结果
        setIsVip(fetchRes ? 1 : 2); // 设置当前结果
      }, 1000);
    }else{
     setIsVip(cache[uId] ? 1 : 2);
    }
  }, [uId]);
  return isVip;
}

function App() {
  const userList = [
    {id: 1, name: 'lion-1'},
    {id: 2, name: 'lion-2'},
    {id: 3, name: 'lion-3'},
  ];
  const [selectIndex, setSelectIndexd] = useState(0);
  const vipStatus = useIsVip(userList[selectIndex].id);
  return (
    <div className="App">
      <select 
        value={selectIndex} 
        onChange={e => setSelectIndexd(+e.target.value)}
      >
        {userList.map((userInfo, index) => (
          <option key={userInfo.id} value={index}>
            {userInfo.name}
          </option>
        ))}
      </select>
      <p>{userList[selectIndex].name} {vipStatus === 1 ? '是' : '不是'}vip</p>
    </div>
  );
}

export default App;
